import {
	handleGetDictData,
} from '@/base/api/common.js';
import {
	copySimpleData
} from "@/sl-uni-sdk/utils/common.js";

//多个页面都会用到的基础数据
function BaseData(apiHandler, dataHandler) {
	this.isInit = false;
	this.apiHandler = apiHandler;
	this.dataHandler = dataHandler;
	this.data = null;
}
BaseData.prototype.getData = async function(options) {
	options = Object.assign({
		//是否强制重新发请求更新数据
		force: false,
		//是否带有全局加载中效果
		loading: true,
		//当验证token失败时跳转到登录页的附加参数字符串
		loginParams: "",
	}, options || {});
	if (this.isInit && !options.force) {
		return copySimpleData(this.data);
	}
	try {
		let data = await this.apiHandler(options);
		if (data) {
			this.isInit = true;
			if (this.dataHandler) {
				data = this.dataHandler(data);
			}
			this.data = data;
		} else {
			this.isInit = false;
			this.data = null;
		}
	} catch (err) {
		console.log("==============>BaseData getData error", err);
		this.isInit = false;
		this.data = null;
	}
	return copySimpleData(this.data);
}

function handleDictData(data) {
	return data.map((el) => ({
		text: el.label,
		value: el.value,
	}));
}

const baseDataObj = {
	//字典数据
	// FEEDBACKTYPE: new BaseData(handleGetDictData('FEEDBACKTYPE'), handleDictData),
	service_type: new BaseData(handleGetDictData('service_type'), handleDictData),
};

export async function getBaseData(key, options) {
	const target = baseDataObj[key];
	if (!target) {
		console.error(`BaseData[${key}]未定义`);
		return null;
	}
	return await target.getData(options);
}